﻿using Core.DataAccess.ApiJson;
using Core.DataAccess.ApiJson.Controllers;
using Grain.Interfaces;
using Grain.State.BaseModule.StorgeStates;
using iTool.ClusterComponent;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Grain.Implements
{
    public class DatabaseConfigurationService : iToolServiceBase<DatabaseConfigurationState>, IDatabaseConfigurationService
    {

        public Task Modify(string title, string connaction, Dictionary<string, TableSchema> schema = null)
        {
            if (this.State.DatabaseConnaction.ContainsKey(title))
            {
                this.State.DatabaseConnaction[title] = connaction;

                if (schema != null)
                {
                    //this.State.DBSchema = schema;
                    string filePath = $"./{title}-tableSchema-new.json";
                    File.WriteAllText(filePath, JsonConvert.SerializeObject(schema));
                }

                this.WriteStateAsync();
            }

            return Task.CompletedTask;
        }

        public Task Register(string title, string connaction)
        {
            if (this.State.DatabaseConnaction.ContainsKey(title))
                this.State.DatabaseConnaction[title] = connaction;
            else
                this.State.DatabaseConnaction.Add(title, connaction);

            this.CheckBuildSchema(title, connaction);

            this.WriteStateAsync();

            return Task.CompletedTask;
        }

        public Task Remove(string title)
        {
            if (this.State.DatabaseConnaction.ContainsKey(title))
            {
                // 配置文件
                string filePath = $"./{title}-tableSchema-new.json";
                bool isFileExists = File.Exists(filePath);
                if (isFileExists)
                {
                    File.Delete(filePath);
                }

                this.State.DatabaseConnaction.Remove(title);
                this.WriteStateAsync();
            }

            return Task.CompletedTask;
        }

        public Task<(string connationString, string schema)> GetConnactionByTitle(string title, bool isReadSchema = false)
        {
            string connationString = string.Empty;

            if (this.State.DatabaseConnaction.ContainsKey(title))
            {
                connationString = this.State.DatabaseConnaction[title];
                if (isReadSchema)
                {
                    this.CheckBuildSchema(title, connationString);
                }
            }

            string filePath = $"./{title}-tableSchema-new.json";

            return Task.FromResult((connationString, isReadSchema ? File.ReadAllText(filePath) : string.Empty));
        }

        public Task<Dictionary<string, string>> GetConnactionList()
        {
            return Task.FromResult(this.State.DatabaseConnaction);
        }


        private void CheckBuildSchema(string title, string connationString)
        {
            // 获取上一份配置文件
            string filePath = $"./{title}-tableSchema-new.json";
            bool isFileExists = File.Exists(filePath);

            if (!isFileExists)
            {
                var databaseSchemaController = new DatabaseSchemaController(ApiJsonDbContext.CreateSqlSugarClient(connationString), null);
                databaseSchemaController.ExportDataBaseToFile(string.Empty, filePath, true);
            }

            // 获取配置文件
            //if (File.Exists(filePath) && this.State.DBSchema.Count < 1 || !isFileExists && File.Exists(filePath))
            //{
            //    var schemaDictionary = JsonConvert.DeserializeObject<Dictionary<string, TableSchema>>(File.ReadAllText(filePath));
            //    this.State.DBSchema = schemaDictionary;
            //    this.WriteStateAsync();
            //}

        }
    }
}
